//Using the basics of JQuery, as I am more than a touch lazy and do not want
//to put too much effort into making sure this works in all browsers from the
//get go.  (If I get a lot of users, I will rethink this, but I will consider
//myself blessed to be in such a situation. Even then, with how small this
//application is, I can't imagine why I would need it to be smaller.)
//
//I do go ahead and hide these methods under a function for a simple
//namespacing.
var CommutersConnectIndex = new function() {


    //We'll begin with the logic necessary to get the form behavior we want.
    //This behavior is simply to toggle the visibility of fieldsets based on
    //whether or not the you have selected that they are a new or an existing
    //user.
    var radioButtons = $("[name=existingUser]");
    radioButtons.change(function(a) {
        $(".existingUsers, .newUsers").slideToggle(250);
    });

    //We have to reference the currently checked value to determine what is
    //shown when the page is first loaded.  (This will really only change if
    //you click that you have signed up, do not login, view a report, and then
    //use the back button.  So, probably rare, but easy to ensure it is
    //correct.)
    $("[name=existingUser]:checked").each(function(index, item) {
        if (item.value == "yes") {
            $(".newUsers").hide();
        } else {
            $(".existingUsers").hide();
        }
    })


    //Our entire application is to show a map.  We place it on the HTML at
    //#map_canvas.
    var map = new google.maps.Map(document.getElementById("map_canvas"), {zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP});

    function moveMapTo(latitude, longitude) {
        map.setCenter(new google.maps.LatLng(latitude, longitude));
    }

    //To indicate reports to the user, a Marker is placed on the map.  A hover is
    //provided with the title of the marker, and a click handler is added to
    //display the provided content on demand.  To keep the map from becomming
    //cluttered with many content windows, the application uses a single instance
    //and simply moves it when needed.  We also track all markers that we have
    //created so that we do not re-add any.  (TODO Collisions?  Cleanup?)
    var infowindow = new google.maps.InfoWindow();
    var curMarkers = new Object()
    function showReport(title, content, latitude, longitude) {
        var pos = new google.maps.LatLng(latitude, longitude);
        if (curMarkers[pos]) return

        var marker = new google.maps.Marker({
            position: pos,
            map: map,
            title: title,
            animation: google.maps.Animation.DROP
        });
        curMarkers[pos] = marker;


        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(content);
            infowindow.open(map,marker);
        });
    }

    //If we don't have geolocation(or your browser doesn't give us the
    //data), we currently default the map to Atlanta.
    function showAtlanta() {
        moveMapTo(33.7546, -84.387);
    }

    if (window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(function(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            moveMapTo(latitude, longitude);
        }, showAtlanta);
    } else {
        showAtlanta();
    }

    google.maps.event.addListener(map, "idle", function(a, b, c) {
        var ne = map.getBounds().getNorthEast();
        var sw = map.getBounds().getSouthWest();
        //And now we fire off a request to get all of the current reports.  This
        //request should return a JSON array of objects with a latitude,
        //longitude, identifier, and a subject.  The latitude and longitude are
        //used to place the marker.  The subject and identifier are used to create
        //the content of the info window.
        $.ajax({
            url: "/reports/inBounds/"+ne.lat()+","+ne.lng()+"/"+sw.lat()+","+sw.lng(),
            success: function(a, b) {
                if (a.results) {
                    var results = a.results;
                    for (var i = 0; i < results.length; i++) {
                        var curReport = results[i];
                        //So... I really need to know the "jquery" way to do
                        //templates.  (As noted elsewhere, most of this work was on
                        //train, where I had no internet...)
                        var reportId = curReport.id;
                        var content = $("<a href='/report/"+reportId+"'/>").append(document.createTextNode(curReport.subject));
                        content = $("<div></div>").append(content)
                        content = content.append("<br/><img src='/report/"+reportId+"/thumbnail' />")
                        content = content[0];
                        showReport("Hello", content, curReport.latitude, curReport.longitude);
                    }
                }
            }
        });
    })
}

